/**
 * 功能:TK_IN_WAREHOUSE 控制器类
 * 开发人员:yaren
 * 创建时间:2012/4/22 12:15:56
 */
package com.towker.frame.controller.warehouse;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oracle.net.aso.s;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.towker.core.page.PageModel;
import com.towker.core.page.PageNav;
import com.towker.core.util.CollectionUtil;
import com.towker.core.util.RefGoodsType;
import com.towker.frame.controller.BaseController;
import com.towker.frame.model.basicData.Goods;
import com.towker.frame.model.purchase.PurchasePlan;
import com.towker.frame.model.sell.Delivery;
import com.towker.frame.model.sell.RefGoods;
import com.towker.frame.model.warehouse.InWarehouse;
import com.towker.frame.model.warehouse.SendBills;
import com.towker.frame.model.warehouse.WarehouseAccounts;
import com.towker.frame.service.basicData.CustomsService;
import com.towker.frame.service.basicData.DepartmentsService;
import com.towker.frame.service.basicData.DepotsService;
import com.towker.frame.service.basicData.GoodsService;
import com.towker.frame.service.basicData.SurplusOrderService;
import com.towker.frame.service.purchase.PurchasePlanService;
import com.towker.frame.service.warehouse.InWarehouseService;
import com.towker.frame.service.warehouse.WarehouseAccountsService;
import com.towker.frame.share.sys.user.UserShare;
import com.towker.web.MyRequest;

//TK_IN_WAREHOUSE
@Controller
@SuppressWarnings("unchecked")
@RequestMapping("/manage/warehouse")
public class InWarehouseController extends BaseController
{
	private InWarehouseService service;
	private CustomsService customsService;//客户信息
	private DepartmentsService departmentsService;//部门信息
	private DepotsService depotsService;//仓库信息
	private GoodsService goodsService;//物品信息
	private WarehouseAccountsService warehouseAccountsService;
	private SurplusOrderService surplusOrderService; 
	private PurchasePlanService purchasePlanService;
	
	//业务对象注入
	public void setPurchasePlanService(PurchasePlanService purchasePlanService)
	{
		this.purchasePlanService = purchasePlanService;
	}
	
	public void setInWarehouseService(InWarehouseService service)
	{
		this.service = service;
	}
	
	public void setCustomsService(CustomsService customsService)
	{
		this.customsService = customsService;
	}
	
	public void setDepartmentsService(DepartmentsService departmentsService)
	{
		this.departmentsService = departmentsService;
	}
	
	public void setDepotsService(DepotsService depotsService)
	{
		this.depotsService = depotsService;
	}
	
	
	public void setGoodsService(GoodsService goodsService)
	{
		this.goodsService = goodsService;
	}
	
	public void setWarehouseAccountsService(WarehouseAccountsService warehouseAccountsService)
	{
		this.warehouseAccountsService = warehouseAccountsService;
	}

	public void setSurplusOrderService(SurplusOrderService surplusOrderService) {
		this.surplusOrderService = surplusOrderService;
	}

	//添加
	@RequestMapping("/addInWarehouse{viewName}")
	public ModelAndView addInWarehouse(HttpServletResponse response, HttpServletRequest request, InWarehouse po, @PathVariable String viewName) throws IOException
	{
		ModelAndView result = null;
		if ("1".equals(viewName))
		{
			result = new ModelAndView();
			Map map = new HashMap();
			List departList = departmentsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//部门信息
			List deportList = depotsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//仓库信息
			result.addObject("departList", departList);
			result.addObject("deportList", deportList);
			result.addObject("dep_code", UserShare.getCurrentUserDepCode(request));
			result.addObject("in_warehouse_code", service.getNewInCode());//入仓单号
			result.setViewName("/manage/warehouse/addInWarehouse.jsp");
		}
		else if ("2".equals(viewName))
		{
			po.setAuthCoCode(UserShare.getCurrentUserCoCode(request));
			//po.setAuthDepCode(UserShare.getCurrentUserDepCode(request));
			po.setCreater_code(UserShare.getCurrentUserCode(request)+"["+UserShare.getCurrentUserName(request)+"]");//获取当前用户代码 名称
			po.setCreater_id(UserShare.getCurrentUserId(request).intValue());//获取当前用户id
			PrintWriter writer = response.getWriter();
			service.add(po);
			MyRequest myRequest = new MyRequest(request);
			String goodsInfo = myRequest.getString("goodsInfo");
			try
			{
				processRefGoods(request, RefGoodsType.INWAREHOUSE_GOODS, po.getId(), goodsInfo);
				//处理库存量,增加
				List<RefGoods> refGoods = refGoodsService.getByInfoType(RefGoodsType.INWAREHOUSE_GOODS.getValue(),po.getId() );
				
				calcGoodsStock(new ArrayList<RefGoods>(), refGoods, surplusOrderService, po.getDepot_code(), po.getAuthCoCode(), true, true);

				writer.write("添加入仓单成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				writer.write("添加入仓单失败！" + e.getCause());
			}
		}
		return result;
	}

	//删除
	@RequestMapping("/delInWarehouse")
	public void delInWarehouse(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		MyRequest req = new MyRequest(request);
		long[] ids = req.getLongArray("keyIndex", 0);
		
		for (Long id : ids) {
			InWarehouse w = service.getById(id);
			if (w != null) {
				List<RefGoods> refOldGoods = refGoodsService.getByInfoType(RefGoodsType.INWAREHOUSE_GOODS.getValue(), id.intValue());
				calcGoodsStock(refOldGoods, new ArrayList<RefGoods>(), surplusOrderService, w.getDepot_code(), w.getAuthCoCode(), false, true);
			}
		}
		
		service.delByIds(CollectionUtil.toLongArray(ids ));
		
		response.sendRedirect(req.getRefererURL());
	}

	//修改
	@RequestMapping("/updInWarehouse{viewName}")
	public ModelAndView updInWarehouse(HttpServletRequest request, HttpServletResponse response, InWarehouse po, @PathVariable String viewName) throws IOException
	{
		ModelAndView result = null;
		MyRequest req = new MyRequest(request);
		if ("1".equals(viewName))
		{
			Long id = req.getLong("keyIndex");
			po = service.getById(id);
			result = new ModelAndView();
			result.addObject("po", po);
			Map map = new HashMap();
			List departList = departmentsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//部门信息
			List deportList = depotsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//仓库信息
			result.addObject("departList", departList);
			result.addObject("deportList", deportList);
			result.addObject("refGoods", refGoodsService.getByInfoType(RefGoodsType.INWAREHOUSE_GOODS.getValue(),new Integer(String.valueOf(id)) ));
			result.setViewName("/manage/warehouse/updInWarehouse.jsp");
		}
		else if ("2".equals(viewName))
		{
			PrintWriter writer = response.getWriter();
			String goodsInfo = req.getString("goodsInfo");
			try
			{
				List<RefGoods> refOldGoods = refGoodsService.getByInfoType(RefGoodsType.INWAREHOUSE_GOODS.getValue(),po.getId() );
				service.update(po);
				processRefGoods(request, RefGoodsType.INWAREHOUSE_GOODS, po.getId(), goodsInfo);
				//处理库存量,增加
				List<RefGoods> refGoods = refGoodsService.getByInfoType(RefGoodsType.INWAREHOUSE_GOODS.getValue(),po.getId() );

				calcGoodsStock(refOldGoods, refGoods, surplusOrderService, po.getDepot_code(), po.getAuthCoCode(), true, true);
				
				writer.write("修改入仓单成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				writer.write("修改入仓单失败！" + e.getCause());
			}
		}
		return result;
	}

	//获得分页
	@RequestMapping("/getInWarehouse")
	public ModelAndView getInWarehouse(HttpServletRequest request,HttpServletResponse response, @RequestParam(value="page", defaultValue="1")int page)
	{
		int pageSize = 10;
		MyRequest req = new MyRequest(request);
		Map map = req.getParameterValueMap(false, true);
		//只查询当前用户所属部门
		map.put("authCoCode", UserShare.getCurrentUserCoCode(request));
		//map.put("authDepCode", UserShare.getCurrentUserDepCode(request));
		PageModel<InWarehouse> pageModel = service.getPage(page, pageSize, map);
		ModelAndView result = new ModelAndView();
		PageNav pageNav = new PageNav(request, pageModel);
		result.addObject("pageModel", pageModel);
		result.addObject("pageNav", pageNav);
		Map depoMap = new HashMap();
		List deportList = depotsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//仓库信息
		result.addObject("deportList", deportList);
		result.setViewName("/manage/warehouse/getInWarehouse.jsp");
		return result;
	}

	//明细
	@RequestMapping("/getInWarehouseById")
	public ModelAndView getInWarehouseById(HttpServletRequest request, HttpServletResponse response)
	{
		InWarehouse po = null;
		MyRequest req = new MyRequest(request);
		Long id = req.getLong("keyIndex");
		po = service.getById(id);
		ModelAndView result = new ModelAndView();
		result.addObject("po", po);
		result.addObject("dep", departmentsService.getByCode(po.getDep_code()));
		result.addObject("depot", depotsService.getByCode(po.getDepot_code()));
		result.setViewName("/manage/warehouse/getInWarehouseById.jsp");
		result.addObject("refGoods", refGoodsService.getByInfoType(RefGoodsType.INWAREHOUSE_GOODS.getValue(),new Integer(String.valueOf(id)) ));
		return result;
	}
	
	//审核
	@RequestMapping("/auditInWarehouse{viewName}")
	public ModelAndView auditInWarehouse(HttpServletRequest request, HttpServletResponse response,@PathVariable String viewName) throws IOException
	{
		ModelAndView result = null;
		InWarehouse po = null;
		MyRequest req = new MyRequest(request);
		Long id = req.getLong("keyIndex");
		po = service.getById(id);
		if("1".equals(viewName)){
			result = new ModelAndView();
			result.addObject("audit", "audit");
			result.addObject("po", po);
			result.setViewName("/manage/warehouse/getInWarehouseById.jsp");
			result.addObject("refGoods", refGoodsService.getByInfoType(RefGoodsType.INWAREHOUSE_GOODS.getValue(),new Integer(String.valueOf(id)) ));
		}else if("2".equals(viewName)) {
			PrintWriter writer = response.getWriter();
			try {
				po.setAudit_status(1);
				po.setStatus(1);
				service.update(po);
				
				this.Bookkeeping(po);
				writer.write("审核成功！");
			}catch (Exception e) {
				e.printStackTrace();
				writer.write("审核失败！" + e.getCause());
			}
		}
		return result;
	}
	
	//记账
	/*@RequestMapping("/accInWarehouse{viewName}")
	public ModelAndView accInWarehouse(HttpServletRequest request, HttpServletResponse response,@PathVariable String viewName) throws IOException
	{
		ModelAndView result = null;
		InWarehouse po = null;
		MyRequest req = new MyRequest(request);
		Long id = req.getLong("keyIndex");
		po = service.getById(id);
		if("1".equals(viewName)){
			result = new ModelAndView();
			result.addObject("acc", "acc");
			result.addObject("po", po);
			result.setViewName("/manage/warehouse/getInWarehouseById.jsp");
			result.addObject("refGoods", refGoodsService.getByInfoType(RefGoodsType.INWAREHOUSE_GOODS.getValue(),new Integer(String.valueOf(id)) ));
		}else if("2".equals(viewName)) {
			PrintWriter writer = response.getWriter();
			try {
				po.setAcc_status(1);
				po.setStatus(3);
				service.update(po);//更新状态
				List<RefGoods> refgoodList = refGoodsService.getByInfoType(RefGoodsType.INWAREHOUSE_GOODS.getValue(), po.getId());
				if (refgoodList!=null && refgoodList.size()!=0) {
					for (int i = 0; i < refgoodList.size(); i++) {
						*//**
						 * 增加库存数量
						 *//*
						RefGoods refGoods = (RefGoods)refgoodList.get(i);
						Goods goods = goodsService.getById(new Long(refGoods.getGoods_id()));
						//更新库存数量
						double stock = refGoods.getAmount()+goods.getStock();
						goods.setStock(stock);
						goodsService.update(goods);
						*//**
						 * 记录到仓库帐中
						 *//*
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						WarehouseAccounts warehouseAccounts = new WarehouseAccounts();
						warehouseAccounts.setAcc_period(po.getAcc_period());//财务统计核算期
						warehouseAccounts.setInfo_type("入仓单");//仓库帐类型
						warehouseAccounts.setGoods_sn(goods.getGoods_sn());//物料代码
						warehouseAccounts.setDep_code(po.getDepot_code());//仓库代码
						warehouseAccounts.setCreate_date(po.getIn_date());//入仓单日期
						warehouseAccounts.setCreate_time(po.getIn_time());//入仓库时间
						warehouseAccounts.setSys_date(format.format(new Date()));//生成仓库帐时间
						warehouseAccounts.setAmount(refGoods.getAmount());//物品数量
						warehouseAccounts.setStock_num(stock);//当前库存数量
						warehouseAccounts.setSend_amount(0);//已下采购单要求送货数量, 根据采购单号 查询采购数量
						String remark = "单号："+po.getIn_warehouse_code()+"，部门："+po.getDep_code()+"";
						warehouseAccounts.setRemark(remark);//凭证号（单号）、部门、客户等>
						warehouseAccountsService.add(warehouseAccounts);
					}
				}
				writer.write("记账成功！");
			}catch (Exception e) {
				e.printStackTrace();
				writer.write("记账失败！" + e.getCause());
			}
		}
		return result;
	}*/
	
	
	/**
	 *记账
	 */
	private void Bookkeeping(InWarehouse po){
		calcWarehouseAccount(warehouseAccountsService, RefGoodsType.INWAREHOUSE_GOODS, po.getId(), po.getDepot_code(), po.getAuthCoCode(), true);
	}
	
	////获得审核通过并且未复制的采购计划申请的数据
	@RequestMapping("/getCopyPurchasePlan")
	public ModelAndView getPurchasePlan(HttpServletRequest request,HttpServletResponse response, @RequestParam(value="page", defaultValue="1")int page)
	{
		int pageSize = 10;
		MyRequest req = new MyRequest(request);
		Map map = req.getParameterValueMap(false, true);
		map.put("copy_status", 0);
		map.put("status", 3);
		//只查询当前用户所属部门
		map.put("authCoCode", UserShare.getCurrentUserCoCode(request));
		//map.put("authDepCode", UserShare.getCurrentUserDepCode(request));
		PageModel<PurchasePlan> pageModel = purchasePlanService.getPage(page, pageSize, map);
		ModelAndView result = new ModelAndView();
		PageNav pageNav = new PageNav(request, pageModel);
		List departList = departmentsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//部门信息
		List deportList = depotsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//仓库信息
		result.addObject("departList", departList);
		result.addObject("deportList", deportList);
		result.addObject("pageModel", pageModel);
		result.addObject("pageNav", pageNav);
		result.setViewName("/manage/warehouse/getCopyPurchasePlan.jsp");
		return result;
	}
	
	//批量复制采购计划申请的数据
	@RequestMapping("/copyPurchasePlan")
	public void copyPurchasePlan(HttpServletRequest request,HttpServletResponse response) throws Exception {
		MyRequest req = new MyRequest(request);
		String sell_dep_code = req.getString("sell_dep_code");
		String depot_code = req.getString("depot_code");
		String acc_period = req.getString("acc_period");
		Long[] idArry = CollectionUtil.toLongArray(req.getLongArray("keyIndex", 0));
		for (int i = 0; i < idArry.length; i++) {
			Long id = req.getLong("keyIndex");
			PurchasePlan purchasePlan = purchasePlanService.getById(id);
			purchasePlan.setCopy_status(1);
			purchasePlanService.update(purchasePlan);
			
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			InWarehouse inwarehouse = new InWarehouse();
			inwarehouse.setIn_warehouse_code(service.getNewInCode());//入仓单号
			inwarehouse.setIn_type(4);//入仓性质
			inwarehouse.setIn_date(new Date());//入仓日期
			inwarehouse.setDepot_code(depot_code);//入仓仓库
			inwarehouse.setAcc_period(acc_period);//财务核算期
			inwarehouse.setDep_code(sell_dep_code);//入仓部门
			inwarehouse.setPur_order_code(purchasePlan.getPlan_sn());//所属采购单号
			
			inwarehouse.setAuthCoCode(UserShare.getCurrentUserCoCode(request));//所属公司代码
			//inwarehouse.setAuthDepCode(UserShare.getCurrentUserDepCode(request));//所属部门代码
			
			service.add(inwarehouse);
			
			List<RefGoods> refGoods = refGoodsService.getByInfoType(RefGoodsType.PURCHASEPLAN_GOODS.getValue(), purchasePlan.getId());
			for (RefGoods refGoods2 : refGoods) {
				refGoods2.setInfo_id(inwarehouse.getId());
				refGoods2.setInfo_type(RefGoodsType.INWAREHOUSE_GOODS.getValue());
				refGoodsService.add(refGoods2);
				//增加库存
				surplusOrderService.addStockAmount(refGoods2.getGoods_id(), inwarehouse.getDepot_code(), inwarehouse.getAuthCoCode(), refGoods2.getAmount(), true);
			}
		}
	}
	
}
